<template>
<div class="cb-main-container">
  <div class="search-box">
    <el-form ref="searchFormRef" :model="searchFormConfig.model" inline>
      <el-form-item prop="name" label="名称">
        <el-input v-model="searchFormConfig.model.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item prop="managerName" label="联系人">
        <el-input v-model="searchFormConfig.model.managerName" placeholder="请输入管理员名称" />
      </el-form-item>
      <el-form-item prop="status" label="状态">
        <el-select v-model="searchFormConfig.model.status" placeholder="请选择状态" style="width: 150px;">
          <el-option v-for="(item, index) in statusEnums" :label="item.label" :value="item.value" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="refresh" @click="doReset">重置</el-button>
        <el-button type="primary" icon="search" @click="doSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="main-content">
    <div class="operation-box">
      <el-button icon="plus" type="primary" @click="onAdd">新增</el-button>
    </div>
    <div class="table-box">
      <el-table :data="tableConfig.data" size="large" empty-text="暂无数据">
        <el-table-column type="index" width="50" />
        <el-table-column property="name" label="名称" />
        <el-table-column property="address" label="地址" show-overflow-tooltip />
        <el-table-column property="managerName" label="联系人" />
        <el-table-column property="managerPhone" label="联系方式" />
        <el-table-column property="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'primary' : 'info'">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="createTime" label="创建时间" />
        <el-table-column label="操作" align="right">
          <template #default="scope">
            <el-button icon="edit" link type="primary" @click="onEdit(scope.row)">编辑</el-button>
            <el-button icon="delete" link type="danger" @click="onDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-box">
      <el-pagination background layout="prev, pager, next" :total="searchFormConfig.model.total" @current-change="handleCurrentChange" />
    </div>
  </div>
</div>

  <!-- 添加/编辑 -->
  <el-dialog v-model="dialogConfig.visible" :title="dialogConfig.title" :width="dialogConfig.width" @close="dialogCloseHandle">
    <el-form ref="formRef" :model="formConfig.model" label-width="86px" :rules="formConfig.rules">
      <el-form-item label="仓库名称" prop="name">
        <el-input v-model="formConfig.model.name" autocomplete="off" placeholder="请填入仓库名称" maxlength="32" />
      </el-form-item>
      <el-form-item label="所在地区" prop="areaCascaderValue">
        <el-cascader style="width: 100%"
            placeholder="请选择所在区域"
            v-model="formConfig.model.areaCascaderValue"
            :options="formConfig.areaOptions"
            :props="formConfig.areaProps"
            @change="areaCascaderHandleChange"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formConfig.model.address" placeholder="请输入详细地址" maxlength="125" />
      </el-form-item>
      <el-form-item label="联系人" prop="managerName">
        <el-input v-model="formConfig.model.managerName" placeholder="请输入联系人名称" maxlength="16" />
      </el-form-item>
      <el-form-item label="联系电话" prop="managerPhone">
        <el-input v-model="formConfig.model.managerPhone" placeholder="请输入联系人电话" maxlength="13" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formConfig.model.status" placeholder="请选择状态">
          <el-option v-for="(item, index) in statusEnums" :label="item.label" :value="item.value" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input type="textarea" :rows="6" v-model="formConfig.model.remarks" placeholder="请输入备注信息" show-word-limit maxlength="500" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onDialogCancel">取消</el-button>
        <el-button type="primary" @click="onDialogConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue"
import { add, edit, pageList, deleteById } from '@/api/erp/warehouse.js'
import { provinceCityTree } from '@/api/common/area.js'
import { isPhone } from '@/util/ValidatorUtil.js'
import { clear } from '@/util/ObjectUtil.js'
import {ElMessageBox} from "element-plus";

defineOptions({
  name: '/erp/baseData/warehouseManage/warehouse'
})

// 表单验证规则
const managerPhoneValidator = (rule, value, callback) => {
  if (value) {
    if (!isPhone(value)) {
      callback(new Error("手机号格式不正确"))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const searchFormRef = ref(null)
const searchFormConfig = reactive({
  model: {
    name: '',
    managerName: '',
    managerPhone: '',
    status: '',
    pageNum: 1,
    pageSize: 10,
    total: 0
  }
})

const formRef = ref(null)
const formConfig = reactive({
  model: {
    id: '',
    name: '',
    provinceId: '',
    cityId: '',
    address: '',
    managerName: '',
    managerPhone: '',
    remarks: '',
    createTime: '',
    updateTime: '',
    areaCascaderValue: [],
    status: ''
  },
  rules: {
    'name': [
      {required: true, message: '名称不能为空', trigger: 'blur'}
    ],
    'structureType': [
      {required: true, message: '类型不能为空', trigger: 'blur'}
    ],
    'areaCascaderValue': [
      {required: true, message: '区域不能为空', trigger: 'blur'}
    ],
    'address': [
      {required: true, message: '详细地址不能为空', trigger: 'blur'}
    ],
    'managerName': [
      {required: true, message: '联系人不能为空', trigger: 'blur'}
    ],
    'managerPhone': [
      {required: true, message: '联系电话不能为空', trigger: 'blur'},
      {validator: managerPhoneValidator, trigger: 'blur'}
    ]
  },
  areaOptions: [],
  areaProps: {
    value: 'id',
    label: 'name'
  }
})

const statusEnums = [
  {label: '禁用', value: 0},
  {label: '启用', value: 1}
]

const getStatusText = (status) => {
  let statusText = '未知'
  for (let item of statusEnums) {
    if (item['value'] === status) {
      statusText = item['label']
      break
    }
  }

  return statusText
}

const tableConfig = reactive({
  data: []
})

const dialogConfig = reactive({
  visible: false,
  title: '新增',
  width: 500
})

//重置
function doReset() {
  searchFormConfig.model.pageNum = 1
  searchFormRef.value.resetFields()
  requestPageList()
}
//搜索
function doSearch() {
  searchFormConfig.model.pageNum = 1
  requestPageList()
}

// 删除
const onDel = (rowData) => {
  ElMessageBox.confirm('确定要删除这条数据吗?', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定'
  }).then(() => {
    deleteById(rowData.id).then(() => {
      requestPageList()
    })
  })
}

//新增
async function onAdd() {
  requestAreas()
  dialogConfig.visible = true
}

// 初始化省市区
const requestAreas = () => {
  provinceCityTree().then(resp => {
    formConfig.areaOptions = resp.data
  })
}

//编辑
const onEdit = async (rowData) => {
  const responseData = await provinceCityTree()
  formConfig.areaOptions = responseData.data

  formConfig.model = {...rowData}
  formConfig.model.areaCascaderValue = [formConfig.model.provinceId, formConfig.model.cityId]

  dialogConfig.visible = true
}

const onDialogCancel = () => {
  dialogConfig.visible = false
}

//提交
const onDialogConfirm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (valid) {
    if (formConfig.model.id) {
      await edit(formConfig.model)
    } else {
      await add(formConfig.model)
    }

    await requestPageList()
    dialogConfig.visible = false
  }
}

//分页处理
function handleCurrentChange(currentPage) {
  searchFormConfig.model.pageNum = currentPage
  requestPageList()
}

function areaCascaderHandleChange(cascaderValue) {
  formConfig.model.provinceId = cascaderValue[0]
  formConfig.model.cityId = cascaderValue[1]
}

// Dialog关闭事件
function dialogCloseHandle() {
  if (!formRef.value) return
  formRef.value.resetFields()

  clear(formConfig.model)
}

const requestPageList = () => {
  pageList(searchFormConfig.model).then(resp => {
    tableConfig.data = resp.data.data
    searchFormConfig.model.total = Number.parseInt(resp.data.total)
  })
}

onMounted(() => {
  requestPageList()
})
</script>

<style scoped lang="scss">
.cb-main-container {
  display: flex;
  flex-direction: column;

  .search-box {
    @include containerStyle;
    padding-bottom: 0;
  }

  .main-content {
    flex: 2;
    @include containerStyle;

    display: flex;
    flex-direction: column;

    .table-box {
      flex: 2;
      margin-bottom: $cb_margin-value;
    }
  }
}
</style>
